<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="计划标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入计划标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划状态 " prop="status">
        <el-select v-model="queryParams.status" style="width: 90px;" clearable >
          <el-option
            v-for="dict in plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划分类" prop="category">
        <el-select v-model="queryParams.category" style="width: 90px;" clearable >
          <el-option
            v-for="dict in plan_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
     
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD hh:mm:ss"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['media:plans:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['media:plans:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['media:plans:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['media:plans:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="plansList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划标题" align="center" prop="title" />
      <el-table-column label="计划描述" align="center" prop="description" />
      
      <el-table-column label="计划状态 " align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="plan_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="计划分类" align="center" prop="category">
        <template #default="scope">
          <dict-tag :options="plan_category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <!-- 是否快到期 -->
       <el-table-column label="到期"  width="50" align="center" prop="isExpiring" >
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.isExpiring">到期</el-tag>
          <el-tag type="success" v-else>正常</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="提醒时间" align="center" prop="reminderTime" >
        <template #default="scope">
          <el-tag type="danger">{{ scope.row.reminderTime }} days</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleInfo(scope.row)" v-hasPermi="['media:issues:query']">查看详情</el-button>
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['media:plans:edit']">修改</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['media:plans:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改个人计划对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="plansRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入计划标题" />
        </el-form-item>
        <!-- 计划分类字典 -->
         <el-form-item label="计划类型" >
          <el-select v-model="form.category" placeholder="请选择" >
            <el-option
              v-for="dict in plan_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
         </el-form-item>
        <el-form-item label="计划描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="计划状态 " prop="status">
          <el-select v-model="form.status" style="width: 90px;"  >
            <el-option
              v-for="dict in plan_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="完成度 " prop="type">
          <el-slider 
            v-model="form.progress" 
            placement="right" 
            :min="0" 
            :max="100" 
            :step="5" 
            show-input />
        </el-form-item>
        <!-- ，单位为分钟，默认不提醒 -->
        <el-form-item label="提醒时间" >
          <el-input-number size="small" v-model="form.reminderTime" :min="1" :max="20"   />&nbsp; days
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情对话框 -->

    <el-dialog :title="title" v-model="detailOpen" width="500px" append-to-body>
      <el-descriptions :column="1" border label-width="100px">
        <el-descriptions-item label="计划标题">
          {{ form.title }}
        </el-descriptions-item>
        <el-descriptions-item label="计划描述">
          <p v-html="form.description"></p>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ form.startDate }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{ form.endDate }}
        </el-descriptions-item>
        <!-- 计划状态 -->
         <el-descriptions-item label="计划状态">
          <dict-tag :options="plan_status" :value="form.status"/>
         </el-descriptions-item>
        <el-descriptions-item label="完成度">
          <el-progress
            :text-inside="true"
            :stroke-width="15"
            :percentage="form.progress"
            status="success"
          />
        </el-descriptions-item>
        <el-descriptions-item label="提醒日期">
          <span>{{ parseTime(form.reminderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="Plans">
import { listPlans, getPlans, delPlans, addPlans, updatePlans } from "@/api/media/plans";


const { proxy } = getCurrentInstance();
const { plan_category,plan_status } = proxy.useDict('plan_category','plan_status');

const plansList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const checkDateRange = (rule, value, callback) => {
  console.log(dateRange.value[0])
  const _startTime = new Date(dateRange.value[0])
  const _endTime = new Date(dateRange.value[1])
  if (!_startTime) {
    return callback(new Error("请选择日期范围"));
  }
  if (isNaN(_startTime.getTime()) || isNaN(_endTime.getTime())) {
    return callback(new Error("日期格式无效"));
  }

  // 计算日期差值（以毫秒为单位）
  const timeDifference = _endTime - _startTime;

  if (timeDifference <= 0) {
    return callback(new Error("结束日期必须晚于开始日期"));
  }
  
  callback();
};

const data = reactive({
  form: {
    reminderTime: 5
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    title: null,
    description: null,
    status: null,
    reminderTime: null,
    createTime: null,
  },
  rules: {
    title: [
      { required: true, message: "计划标题不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "计划描述不能为空", trigger: "blur" }
    ],
    dateRange:[
      { required: true, validator: checkDateRange, trigger: "blur"}
    ]
  
  }
});

const { queryParams, form, rules } = toRefs(data);


/**页面更新执行函数 */
// onUpdated(() => {
//   //获取当前时间
//   const now = new Date();
//   getList()

// });

/** 查询个人计划列表 */
function getList() {
  loading.value = true;
  listPlans(queryParams.value).then(response => {
    plansList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    planId: null,
    userId: null,
    title: null,
    description: null,
    startDate: null,
    endDate: null,
    status: null,
    reminderTime: 5,
    createTime: null,
    updateTime: null,
  };
  dateRange.value = [];
  proxy.resetForm("plansRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.planId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加个人计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _planId = row.planId || ids.value
  getPlans(_planId).then(response => {
    form.value = response.data;
    dateRange.value = [response.data.startDate, response.data.endDate];
    open.value = true;
    title.value = "修改个人计划";
  });
}

/** 查看详情按钮操作 */
const detailOpen = ref(false);
function handleInfo(row) {
  reset();
  const _planId = row.planId;
  getPlans(_planId).then(response => {
    form.value = response.data;
    dateRange.value = [response.data.startDate, response.data.endDate]; // 设置日期范围

    // 计算提醒时间（结束日期减去提前提醒的分钟数）
    const endDate = new Date(form.value.endDate);
    const reminderMinutes = parseInt(form.value.reminderTime, 10) || 0; // 确保 reminderTime 是数字
    const reminderDate = endDate.getTime() - reminderMinutes * 60 * 1000;
    form.value.reminderTime = reminderDate; // 格式化日期

    console.log(form.value.reminderTime);

    detailOpen.value = true;
    title.value = "查看详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["plansRef"].validate(valid => {
    if (valid) {
      if (form.value.planId != null) {
        updatePlans(proxy.addDateRange(form.value, dateRange.value)).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlans(proxy.addDateRange(form.value, dateRange.value)).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _planIds = row.planId || ids.value;
  proxy.$modal.confirm('是否确认删除个人计划编号为"' + _planIds + '"的数据项？').then(function() {
    return delPlans(_planIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('media/plans/export', {
    ...queryParams.value
  }, `plans_${new Date().getTime()}.xlsx`)
}

getList();
</script>
